import Taro, { Component } from "@tarojs/taro";
import { View, Text, Input } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { $Req } from "@utils";
import {
  AtButton,
  AtInput
} from "taro-ui";
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)

export default class Index extends Component {
  config = {
    navigationBarTitleText: "支付密码管理",
  };

  constructor(props) {
    super(...arguments);
    this.state = {
      pwdVal: '',  //输入的密码
      payFocus: true, //文本框焦点
      code: '', // 验证码
      phoneNum: '', // 从全局变量中获取
      loading: false,
      yztime: 59,
      phone: "",
      isPwdFlag: null,
      newPwd: ""
    };
  }

  async componentDidShow() {
    let userInfo = this.props.userModel.userInfo;
    let userPhone = Taro.getStorageSync("userPhone");
    if (userPhone) {
      this.setState({
        phone: userPhone
      })
    } else {
      Taro.showToast({
        title: "手机号码不存在，请重新登录",
        icon: "none"
      })
    }


    let { code, data } = await $Req({
      type: "get",
      url: "/indexUser/checkHavePayPassword",
      data: { userId: userInfo.userId },
    });

    if (code == 200) {
      this.setState({
        isPwdFlag: data
      })
    }
  }

  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer = () => {
    /**获取输入的密码**/
    var val = this.state.pwdVal;
	/**在这调用支付接口**/
    this.setState({ payFocus: false });
    console.log(val);

  }
  /**
   * 获取焦点
   */
  getFocus = () => {
    this.setState({ payFocus: true });
  }
  /**
   * 输入密码监听
   */
  inputPwd = (e) => {
      this.setState({ pwdVal: e.detail.value });

      if (e.detail.value.length >= 6){
        this.hidePayLayer();
      }
  }


   codetimer = async () => {
    let { yztime, phone, loading } = this.state;

    if (loading) {
      return false;
    }

    let siv = setInterval(() => {
      if (yztime <= 0) {
        clearInterval(siv);
        this.setState({
          loading: false,
          yztime: 59
        })
      } else {
        yztime-- 
        this.setState({ 
          yztime
        })
      }
    }, 1000);

    let { code, data } = await $Req({
      type: "post",
      url: "/user/sendMsgCode",
      data: {
        type: 0,
        phone
      }
    });
    
    if (code != 200) return false;

    Taro.showToast({
      title: "发送成功！",
      icon: "none"
    })
  }

  handleChangeCode = code => {
    this.setState({
      code
    })
  }


  getPhoneCode = (e) => {
    e.preventDefault();
    this.codetimer();
    this.setState({ loading: true });
   
  }

  addOrEditPwd = async () => {
    let { pwdVal, code, phone, isPwdFlag, newPwd } = this.state;
    let { flag, price, ordersNo } = this.$router.params;

    if (!pwdVal || isNaN(pwdVal)) {
      Taro.showToast({
        title: "支付密码不能为空!",
        icon:"none"
      })
      return false;
    }

    // 编辑和添加密码
    if (!flag && !price) {
      if (!code || isNaN(code)) {
        Taro.showToast({
          title: "验证码必须是数字!",
          icon:"none"
        })
        return false;
      }


      let res = await $Req({
        type: "post",
        url: "/user/checkMsgCode",
        data: { code, phone, type: 0 },
      });
  
      if (res.code != 200) {
        Taro.showToast({
          title: "验证码错误，请重新输入!",
          icon:"none"
        })
        return false;
      }
  
      let url = ""
      let data = {};
      // 添加
      if (!isPwdFlag) {
        url = "/indexUser/addPayPassword"
        data = {userId: this.props.userModel.userInfo.userId, password: pwdVal}
      }
      // 编辑 
      else {
        if (!newPwd || isNaN(newPwd)) {
          Taro.showToast({
            title: "新支付密码不能为空，且必须是数字!",
            icon:"none"
          })
          return false;
        }
  
        url = "/indexUser/updatePayPassword"
        data = { userId: this.props.userModel.userInfo.userId, password: newPwd, passwordOld: pwdVal}
      }
  
      let options = await $Req({
        type: "get",
        url: url,
        data: data,
      });
  
      if (options.code == 200) {
        if (!isPwdFlag) {
          Taro.showToast({
            title: "添加成功!",
            icon:"none"
          })
        } else {
          Taro.showToast({
            title: "编辑成功!",
            icon:"none"
          })
        }
  
        setTimeout(() => {
          Taro.navigateBack({
            delta: 1,
          });
        }, 600)
      }
    } else { // 验证支付密码
      let { data, code, message } = await $Req({
        type: "get",
        url: "/indexUser/checkPayPassword",
        data: {
          password: pwdVal,
          userId: this.props.userModel.userInfo.userId
        },
      });

      if (code == 200) {
        Taro.setStorageSync("syPay", "ok");
        if (this.$router.params.ordersNo) {
          Taro.setStorageSync("ordersNo", this.$router.params.ordersNo);
        }
        
        setTimeout(() => {
          Taro.navigateBack({
            delta: 1,
          });
        }, 600)
      } else {
        Taro.showToast({
          title: message,
          icon:"none"
        })
      }
    }
  }

  getPhone = phone => phone.substring(0,3) + "****" + phone.substring(7)
  
  render() {
    let  { pwdVal, code, loading, yztime, phone, isPwdFlag } = this.state;
    let { flag, price, yzpwd } = this.$router.params;

    return (
      <View className="layer">
        <View className="layer-container">
          <View style={{ textAlign: "center" }}>
            <Text style={{ fontSize: 16, color: "#1A1A1A" }}>{!isPwdFlag ? "添加支付密码": flag && price ? "验证支付密码" : yzpwd ? "转账验证支付密码" : "编辑支付密码"}</Text>
          </View>

          {
            flag && price ?
            <View>
              <View style={{ textAlign: "center" }}>
                <Text style={{ fontSize: "12PX", color: "#ccc", marginTop: "20PX" }}>需要支付</Text>
              </View>

              <View style={{ textAlign: "center" }}>
                <Text style={{ fontSize: "24PX", color: "#1A1A1A", marginTop: "20PX" }}>￥{price}</Text>
              </View>
            </View>
          :
            null
          }
          

          <View>
              <View className='input_main'>
                  <View className='input_row' onClick={this.getFocus}>
                    {
                      [0,0,0,0,0,0].map((el, index) => (
                        <View className='pwd_item' key={index} >
                            {
                              pwdVal.length > index ? <Text></Text> : null
                            }
                        </View>
                      ))
                    }
                      
                  </View>
                  <Input className='input_control' password type='number' holdKeyboard={true} focus={this.state.payFocus} onInput={this.inputPwd} maxlength='6'/>
              </View>
              
              {/* 验证码 */}
              <View style={{ marginTop: "30PX" }}>
                {
                  isPwdFlag && (!flag && !price ) ?
                    <AtInput
                      title='新支付密码'
                      maxLength={6}
                      type='number'
                      placeholder='请输入新支付密码'
                      onChange={(val) => {
                        console.log(val);
                        this.setState({
                          newPwd: val
                        })
                      }}
                  />
                  :null
                }
                {
                  !flag && !price ?
                    <View>
                      <AtInput
                        disabled
                        title='手机号码'
                        type='text'
                        placeholder='手机号码'
                        value={this.getPhone(phone)}
                      />
                      <AtInput
                        clear
                        type='number'
                        maxLength='6'
                        placeholder='请输入验证码'
                        value={code}
                        onChange={this.handleChangeCode}
                      >
                        <View className="update-phone-code" onClick={this.getPhoneCode}>
                        {loading ? yztime + '秒' : '获取验证码'}
                        </View>
                      </AtInput>
                    </View>
                  :
                  null
                }
                
                <View style={{marginTop: "20PX"}}>
                  <AtButton type='primary' onClick={this.addOrEditPwd}>确定</AtButton>
                </View>
              </View>
          </View>
        </View>
      </View>
    );
  }
}
